package com.xlx.ui.controller;

import com.alibaba.fastjson.JSON;
import com.xlx.ui.domain.DTO.Client;
import com.xlx.ui.domain.MO.Friends;
import com.xlx.ui.domain.MO.Message;
import com.xlx.ui.service.FriendsService;
import com.xlx.ui.service.MessageService;
import com.xlx.ui.util.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Description:
 * @author: 张川
 * @date: 2021-03-31 14:45
 */
@Slf4j
@ServerEndpoint("/user/{id}")
@Component
public class MessageWebsocket {

    public static Map<String, Client> clients = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("id")Integer id) {
        Client client = new Client();
        client.setSession(session);
        client.setSessionId(session.getId());
        client.setUserId(id);
        clients.put(session.getId(),client);
        FriendsService friendsService = SpringContextUtils.getBean(FriendsService.class);
        Friends friends = new Friends();
        friends.setActive(1);
        friends.setFriendsid(id);
        friendsService.setActive(friends);
        log.info("有新的客户端连接了: {},共{}个", id,clients.size());
    }

    /**
     * 客户端关闭
     * @param session session
     */
    @OnClose
    public void onClose(Session session) {
        //将掉线的用户移除在线的组里
        log.info("有用户断开了, id为:{}", session.getId());
        FriendsService friendsService = SpringContextUtils.getBean(FriendsService.class);
        Friends friends = new Friends();
        friends.setActive(0);
        friends.setFriendsid(clients.get(session.getId()).getUserId());
        friendsService.setActive(friends);
        clients.remove(session.getId());
    }

    /**
     * 发生错误
     * @param throwable e
     */
    @OnError
    public void onError(Throwable throwable) {
       log.error(throwable.getMessage());
    }

    /**
     * 收到客户端发来消息
     * @param message  消息对象
     */
    @OnMessage
    public void onMessage(String message) {
        log.info("服务端收到客户端发来的消息: {}", message);
        Message message1 = JSON.parseObject(message, Message.class);
        MessageService messageService = SpringContextUtils.getBean(MessageService.class);
        messageService.add(message1);
        messageService.receive(message1);
    }


}
